<template>
  <div class="p-2 modal_main">
    <el-button link :icon="Back" class="mt-2 mb-2" @click="handleBack">返回</el-button>
    <!-- <el-tabs v-model="activeName">
      <el-tab-pane label="算法类型" :name="0">
        <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
          <div v-show="showSearch" class="mb-[10px]">
            <el-card shadow="hover">
              <el-form ref="queryFormRef" :model="queryParams" :inline="true" size="small" label-width="80">
                <el-form-item label="所属步骤" prop="stepName">
                  <el-select v-model="queryParams.stepName" clearable @change="handleStepChange">
                    <el-option v-for="(item, index) in pageSteps" :key="'name' + index" :label="item.label" :value="item.label" />
                  </el-select>
                </el-form-item>
                <el-form-item label="算法名称" prop="algorithmName">
                  <el-select v-model="queryParams.algorithmName" clearable>
                    <el-option v-for="(item, index) in pageNames" :key="'name' + index" :label="item.algorithmName" :value="item.algorithmName" />
                  </el-select>
                </el-form-item>
                <el-form-item style="padding-left: 80px">
                  <el-button size="small" type="primary" icon="search" @click="handleQuery">搜索</el-button>
                  <el-button size="small" icon="Refresh" @click="resetQuery">重置</el-button>
                </el-form-item>
              </el-form>
            </el-card>
          </div>
        </transition>

        <el-card shadow="hover">
          <template #header>
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button v-hasPermi="['process:data:batchdownload']" size="small" type="primary" plain @click="handleBatchDownload"
                  >批量下载数据</el-button
                >
              </el-col>
              <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
            </el-row>
          </template>

          <el-table v-if="showTable" v-loading="loading" :data="tableDatas" @selection-change="handleSelectionChange">
            <el-table-column width="50" type="selection" align="center"></el-table-column>
            <el-table-column type="expand">
              <template #default="props">
                <div m="4">
                  <el-table :data="props.row.fileInfoList" @selection-change="handleChildrenSelectionChange">
                    <el-table-column width="50" type="selection" align="center"></el-table-column>
                    <el-table-column label="结果数据名称" prop="fileName" />
                    <el-table-column label="数据格式" prop="fileFormat" />
                    <el-table-column label="数据大小" prop="size">
                      <template #default="scope">
                        {{ getSizeStr(scope.row.size) }}
                      </template>
                    </el-table-column>
                    <el-table-column align="center" width="200" fixed="right">
                      <template #default="scope">
                        <el-button v-hasPermi="['process:data:downloaddata']" size="small" link type="primary" @click="handleDownload(scope.row)">
                          下载数据
                        </el-button>
                        <el-button v-hasPermi="['process:data:view']" size="small" link type="primary" @click="handleView(scope.row)">查看</el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="所属步骤" align="center" prop="stepName"></el-table-column>
            <el-table-column label="算法名称" align="center" prop="algorithmName"></el-table-column>
            <el-table-column label="操作" align="center" width="150" fixed="right">
              <template #default="scope">
                <el-button v-hasPermi="['process:data:download']" size="small" link type="primary" @click="handleDownload2(scope.row)"
                  >下载数据</el-button
                >
                <el-button v-hasPermi="['process:data:downloadprogram']" size="small" link type="primary" @click="handleDownloadProgram(scope.row)">
                  下载程序
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-tab-pane> -->
    <!-- <el-tab-pane label="文件类型" :name="1"> -->
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch2" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef2" :model="queryParams2" :inline="true" size="small" label-width="80">
            <el-form-item label="文件名" prop="fileName">
              <el-input v-model="queryParams2.fileName" placeholder="请输入" clearable></el-input>
            </el-form-item>
            <el-form-item style="padding-left: 80px">
              <el-button size="small" type="primary" icon="search" @click="handleQuery2">搜索</el-button>
              <el-button size="small" icon="Refresh" @click="resetQuery2">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="hover">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPermi="['process:data:batchdownload']" size="small" type="primary" plain @click="handleBatchDownload2"
              >批量下载</el-button
            >
          </el-col>
          <right-toolbar v-model:showSearch="showSearch2" @query-table="getList2"></right-toolbar>
        </el-row>
      </template>

      <el-table
        v-if="showTable2"
        v-loading="loading"
        :data="tableDatas2"
        row-key="id"
        :tree-props="{ checkStrictly: false }"
        @selection-change="handleSelectionChange"
      >
        <el-table-column width="50" type="selection" align="center"></el-table-column>
        <el-table-column label="文件名" prop="fileName"></el-table-column>
        <el-table-column label="文件大小" align="center" prop="size">
          <template #default="scope">
            {{ scope.row.directory ? '-' : getSizeStr(scope.row.size) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="100" fixed="right">
          <template #default="scope">
            <el-button v-hasPermi="['process:data:download']" size="small" link type="primary" @click="handleDownload3(scope.row)">下载</el-button>
            <el-button
              v-if="!scope.row.directory"
              v-hasPermi="['process:data:download']"
              size="small"
              link
              type="primary"
              @click="handleView(scope.row)"
              >查看</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- </el-tab-pane>
    </el-tabs> -->
    <el-dialog v-model="dialogVisible" title="文件预览" width="90%" :before-close="handleDialogClose">
      <!-- <vue-office-docx :src="docx" style="height: calc(100vh - 120px)" @rendered="renderedHandler" @error="errorHandler" /> -->
      <iframe :src="fileUrl" style="height: calc(100vh - 240px); width: 100%; border: 0" />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleDialogClose">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ProcessDataView" lang="ts">
import { Back } from '@element-plus/icons-vue';
import { steps } from '@/api/loadProcessingAlgorithm/index';
import { getAlgorithmList } from '@/api/loadProcessingAlgorithm/loadAlgorithmManagement/index';
import { geTaskResultList, downloadFiles, queryFileList, downloadProgram } from '@/api/loadProcessingAlgorithm/loadTaskManagement/index';
import { resultDataVO } from '@/api/loadProcessingAlgorithm/loadTaskManagement/type';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const router = useRouter();
const route = useRoute();
const loadExperimentId = Number(route.query.id);
const loadType = route.query.loadType;
const tableDatas = ref<resultDataVO[]>();
const showTable = ref(true);
const loading = ref(false);
const showSearch = ref(true);
const activeName = ref(0);
const queryFormRef = ref<ElFormInstance>();
const detailDialogShow = ref(false);
const pageNames = ref([]);
const pageSteps = ref(steps);
const dialogVisible = ref(false);
const fileUrl = ref('');
const multipleSelection = ref([]);
const multipleChildrenSelection = ref([]);
const queryParams = reactive({
  loadExperimentId: loadExperimentId,
  algorithmName: '',
  stepName: ''
});
const handleBack = () => {
  router.back();
};
const getAlgorithms = async (step) => {
  const obj = {
    step: step,
    loadType: loadType,
    pageNum: 1,
    pageSize: 99
  };
  const res = await getAlgorithmList(obj);
  return res.rows;
};
const handleStepChange = async (val?) => {
  let obj = null;
  if (val) {
    obj = pageSteps.value.find((item) => item.label === val);
  }
  const step = obj ? Number(obj.value) : undefined;
  pageNames.value = await getAlgorithms(step);
};
const getSizeStr = (size) => {
  if (size < 1024) {
    return Number(size).toFixed(2) + 'KB';
  } else if (size > 1023 && size < 1024 * 1024) {
    return Number(size / 1024).toFixed(2) + 'MB';
  } else {
    return Number(size / 1024 / 1024).toFixed(2) + 'GB';
  }
};
const downloadFile = (res, fileName) => {
  const blob = new Blob([res]);
  const objUrl = URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.setAttribute('href', objUrl);
  link.setAttribute('download', fileName);
  link.style.display = 'none';
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};
const handleBatchDownload = async () => {
  if (!multipleSelection.value.length && !multipleChildrenSelection.value.length) {
    await proxy?.$modal.msgWarning('请选择数据！');
    return false;
  }
  let arr = [];
  multipleSelection.value.forEach((item) => {
    const newArr = item.fileInfoList.map((item) => item.filePath);
    arr = [...arr, ...newArr];
  });
  multipleChildrenSelection.value.forEach((item) => {
    arr.push(item.filePath);
  });
  const res = await downloadFiles(arr);
  const fileName = '算法结果' + '.zip';
  downloadFile(res, fileName);
};
const handleDownload = async (data) => {
  const arr = [data.filePath];
  const res = await downloadFiles(arr);
  const fileName = data.fileName + '.' + data.fileFormat;
  downloadFile(res, fileName);
};
const handleDownload2 = async (data) => {
  const arr = data.fileInfoList.map((item) => item.filePath);
  const res = await downloadFiles(arr);
  const fileName = data.algorithmName + '.zip';
  downloadFile(res, fileName);
};
const handleDownloadProgram = async (row) => {
  const formData = new FormData();
  formData.append('algorithmId', row.algorithmId);
  formData.append('loadExperimentId', row.loadExperimentId);
  const res = await downloadProgram(formData);
  const fileName = row.algorithmName + '.py';
  downloadFile(res, fileName);
};
const getLeafIds = (nodes) => {
  let leafNodes = [];
  nodes.forEach((item) => {
    if (!item.directory) {
      leafNodes.push(item.id);
    } else {
      if (item.children.length) {
        leafNodes = leafNodes.concat(getLeafIds(item.children));
      }
    }
  });
  return leafNodes;
};
const handleBatchDownload2 = async () => {
  if (!multipleSelection.value.length && !multipleSelection.value.length) {
    await proxy?.$modal.msgWarning('请选择数据！');
    return false;
  }
  const arr = getLeafIds(multipleSelection.value);
  const ids = [...new Set(arr)];
  const res = await downloadFiles(ids);
  const fileName = '文件结果' + '.zip';
  downloadFile(res, fileName);
};
const handleView = async (data) => {
  const arr = [data.id];
  const res = await downloadFiles(arr);
  const blob = new Blob([res]);
  const showFile = URL.createObjectURL(blob);
  fileUrl.value = showFile;
  dialogVisible.value = true;
};
const handleSelectionChange = (val) => {
  multipleSelection.value = val;
};
const handleChildrenSelectionChange = (val) => {
  multipleChildrenSelection.value = val;
};
const handleDialogClose = () => {
  dialogVisible.value = false;
};

/** 查询模型列表 */
const getList = async () => {
  loading.value = true;
  const response = await geTaskResultList(queryParams);
  tableDatas.value = response;
  loading.value = false;
  showTable.value = true;
};
/** 搜索按钮操作 */
const handleQuery = () => {
  getList();
};
/** 重置按钮操作 */
const resetQuery = () => {
  showTable.value = false;
  queryFormRef.value?.resetFields();
  handleQuery();
};
//文件类型
const showSearch2 = ref(true);
const queryParams2 = reactive({
  loadExperimentId: loadExperimentId,
  fileName: ''
});
const tableDatas2 = ref<any>([]);
const showTable2 = ref(true);
const queryFormRef2 = ref<ElFormInstance>();
/** 查询模型列表 */
const getList2 = async () => {
  loading.value = true;
  const formData = new FormData();
  formData.append('loadExperimentId', String(loadExperimentId));
  formData.append('fileName', queryParams2.fileName);
  const response = await queryFileList(formData);
  tableDatas2.value = response.children;
  loading.value = false;
  showTable.value = true;
};
/** 搜索按钮操作 */
const handleQuery2 = () => {
  getList2();
};
/** 重置按钮操作 */
const resetQuery2 = () => {
  showTable2.value = true;
  queryFormRef2.value?.resetFields();
  handleQuery2();
};
const handleDownload3 = async (data) => {
  const arr = getLeafIds([data]);
  const ids = [...new Set(arr)];
  const res = await downloadFiles(ids);
  const fileName = data.directory ? data.fileName + '.zip' : data.fileName;
  downloadFile(res, fileName);
};
onMounted(() => {
  handleStepChange();
  getList();
  getList2();
});
</script>
<style lang="scss" scoped>
.modal_main {
  height: calc(100vh - 84px);
  overflow: auto;
}
.pagenation {
  display: flex;
  justify-content: end;
  margin-top: 10px;
}
.dialog-footer {
  text-align: center;
}
:deep(.el-upload) {
  display: block;
}
</style>
